package cn.xfdzx.android.apps.shop.activity.myshop;


import android.app.Dialog;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXLivePushConfig;
import com.tencent.rtmp.TXLivePusher;
import com.tencent.rtmp.TXLog;
import com.tencent.rtmp.ui.TXCloudVideoView;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.IllegalFormatCodePointException;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import MTT.ThirdAppInfoNew;
import butterknife.BindView;
import butterknife.OnClick;
import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.activity.ruzhu.XFDShopInActivity;
import cn.xfdzx.android.apps.shop.adapter.HomeVPAdapter;
import cn.xfdzx.android.apps.shop.adapter.VideoGoodListAdapter;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpActivity;
import cn.xfdzx.android.apps.shop.bean.CreatePusherBeen;
import cn.xfdzx.android.apps.shop.bean.CustomerMsgBeen;
import cn.xfdzx.android.apps.shop.bean.PusherEventBean;
import cn.xfdzx.android.apps.shop.bean.UpdateNumPriceBeen;
import cn.xfdzx.android.apps.shop.bean.UploadImgBeen;
import cn.xfdzx.android.apps.shop.bean.LogininfoBean;
import cn.xfdzx.android.apps.shop.bean.VideoAvatarListBeen;
import cn.xfdzx.android.apps.shop.bean.VideoEndBeen;
import cn.xfdzx.android.apps.shop.bean.VideoRoomGoodListBeen;
import cn.xfdzx.android.apps.shop.beauty.BeautyPanel;
import cn.xfdzx.android.apps.shop.contract.CreatePusherContract;
import cn.xfdzx.android.apps.shop.contract.ItemClickListener;
import cn.xfdzx.android.apps.shop.demo.common.TCLiveRoomMgr;
import cn.xfdzx.android.apps.shop.demo.common.activity.ErrorDialogFragment;
import cn.xfdzx.android.apps.shop.demo.common.utils.TCConstants;
import cn.xfdzx.android.apps.shop.demo.common.widget.TCInputTextMsgDialog;
import cn.xfdzx.android.apps.shop.demo.common.widget.TCSwipeAnimationController;
import cn.xfdzx.android.apps.shop.demo.common.widget.TCVideoWidget;
import cn.xfdzx.android.apps.shop.demo.common.widget.TCVideoWidgetList;
import cn.xfdzx.android.apps.shop.demo.common.widget.danmaku.TCDanmuMgr;
import cn.xfdzx.android.apps.shop.demo.common.widget.like.TCHeartLayout;
import cn.xfdzx.android.apps.shop.demo.liveroom.ILiveRoomListener;
import cn.xfdzx.android.apps.shop.demo.liveroom.LiveRoom;
import cn.xfdzx.android.apps.shop.demo.liveroom.roomutil.commondef.PusherInfo;
import cn.xfdzx.android.apps.shop.demo.liveroom.roomutil.im.TCChatEntity;
import cn.xfdzx.android.apps.shop.demo.liveroom.roomutil.im.TCChatMsgListAdapter;
import cn.xfdzx.android.apps.shop.demo.liveroom.roomutil.im.TCSimpleUserInfo;
import cn.xfdzx.android.apps.shop.demo.liveroom.roomutil.login.JoinRoomSuccessEvent;
import cn.xfdzx.android.apps.shop.demo.liveroom.roomutil.login.TCUserMgr;
import cn.xfdzx.android.apps.shop.evenbus.BuyLiveGoodsMessage;
import cn.xfdzx.android.apps.shop.evenbus.LiveAllCountListMessage;
import cn.xfdzx.android.apps.shop.fragment.LiveAllCountFragment;
import cn.xfdzx.android.apps.shop.fragment.video.HotFragment;
import cn.xfdzx.android.apps.shop.fragment.video.MyFocusLiveFragment;
import cn.xfdzx.android.apps.shop.presenter.CreatePusherPresenter;
import cn.xfdzx.android.apps.shop.util.EmptyUtil;
import cn.xfdzx.android.apps.shop.util.GlideEngine;
import cn.xfdzx.android.apps.shop.util.ProgressDialog;
import cn.xfdzx.android.apps.shop.util.SendValidateTimerUtil;
import cn.xfdzx.android.apps.shop.util.ShopCarPopupWindow;
import cn.xfdzx.android.apps.shop.util.StatusBarUtil;
import cn.xfdzx.android.apps.shop.util.Utils;
import cn.xfdzx.android.apps.shop.util.UtilsData;
import cn.xfdzx.android.apps.shop.util.UtilsLog;
import cn.xfdzx.android.apps.shop.video.PusherBeautyKit;
import cn.xfdzx.android.apps.shop.video.VideoActivity;
import cn.xfdzx.android.apps.shop.video.VideoDetailActivity;
import cn.xfdzx.android.apps.shop.video.VideoShopGoodActivity;

import cn.xfdzx.android.apps.shop.widget.CustomerPopwindow;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static cn.xfdzx.android.apps.shop.apps.Constants.APP_TOKEN;
import static cn.xfdzx.android.apps.shop.apps.Constants.START_CODE;

/**
 * 推流页面
 */
public class CreatePusherActivity extends BaseMvpActivity<CreatePusherPresenter> implements ItemClickListener, CreatePusherContract.View
        , ILiveRoomListener, TCInputTextMsgDialog.OnTextSendListener {
    private static final String TAG = VideoActivity.class.getSimpleName();
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_cover)
    ImageView ivCover;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.iv_logo)
    ImageView ivLogo;
    @BindView(R.id.view_mohu)
    View viewMohu;
    @BindView(R.id.view_feng_mian_bg)
    View viewFengMianBg;
    @BindView(R.id.tv_zhibo_state)
    TextView tvZhiboState;//直播状态
    @BindView(R.id.tv_fengmian)
    TextView tvFengmian;//封面
    @BindView(R.id.tv_cumulative_watch)
    TextView tvCumulativeWatch;//累计观看
    @BindView(R.id.tv_online_num)
    TextView tvOnlineNum;//在线人数
    @BindView(R.id.tv_pay_order_num)
    TextView tvPayOrderNum;//支付订单数
    @BindView(R.id.tv_pay_money)
    TextView tvPayMoney;//支付金额
    @BindView(R.id.tv_cumulative_watch_text)
    TextView tvCumulativeWatchText;
    @BindView(R.id.tv_online_num_text)
    TextView tvOnlineNumText;
    @BindView(R.id.tv_pay_order_num_text)
    TextView tvPayOrderNumText;
    @BindView(R.id.tv_pay_money_text)
    TextView tvPayMoneyText;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_select_good)
    TextView tvSelectGood;
    @BindView(R.id.rl_select_good)
    RelativeLayout rlSelectGood;
    @BindView(R.id.ll_meiyan)
    LinearLayout llMeiyan;
    @BindView(R.id.ll_lvjing)
    LinearLayout llLvjing;
    @BindView(R.id.ll_fanzhuan)
    LinearLayout llFanzhuan;
    @BindView(R.id.tv_start)
    TextView tvStart;
    @BindView(R.id.iv_video_set)
    ImageView ivVideoSet;
    @BindView(R.id.rl_end_video)
    RelativeLayout rlEndVideo;
    /**
     * SDK 提供的类
     */
    private TXLivePushConfig mLivePushConfig;                // SDK 推流 config
    private TXLivePusher mLivePusher;                    // SDK 推流类
    private TXCloudVideoView mPusherView;                    // SDK 推流本地预览类
    /**
     * 控件
     */

    private BeautyPanel mBeautyPanelView;              // 美颜模块pannel
    /**
     * 默认美颜参数
     */
    private int mBeautyLevel = 5;            // 美颜等级
    private int mBeautyStyle = TXLiveConstants.BEAUTY_STYLE_SMOOTH; // 美颜样式
    private int mWhiteningLevel = 3;            // 美白等级
    private int mRuddyLevel = 2;            // 红润等级
    private boolean mFrontCamera = true;

    /**
     * 其他参数
     */
    private boolean mIsUseCamera = false;
    private int mCurrentVideoResolution = TXLiveConstants.VIDEO_RESOLUTION_TYPE_540_960;   // 当前分辨率
    private boolean mIsPushing;                     // 当前是否正在推流
    private Bitmap mWaterMarkBitmap;               // 水印

    String rtmpURL = " "; //此处填写您的 rtmp 推流地址
    int roomId; //直播间id

    private Dialog dialog;
    //    private ShopCarPopupWindow select_HSping_PW;
    private ShopCarPopupWindow select_Set_PW;
    private Context mContext;
    protected Handler handler = new Handler();
    private String image_cover;//封面图

    /**
     * IM聊天室相关
     */
    @BindView(R.id.btn_message_input)
    TextView btn_message_input;//文本输入
    @BindView(R.id.tool_bar)
    RelativeLayout tool_bar;//底部布局
    @BindView(R.id.btn_goods)
    ImageView btnGoods;//购物袋
    @BindView(R.id.tv_video_end_length)
    TextView tvVideoEndLength;//直播时长
    @BindView(R.id.tv_pop)
    TextView tv_pop;//pop动画
    @BindView(R.id.rl_zan)
    RelativeLayout rl_zan;//赞布局
    @BindView(R.id.tv_zancount)
    TextView tv_zancount;//点赞数量
    @BindView(R.id.rl_onlinecount)
    RelativeLayout rl_onlinecount;//在线人数布局

    private TCInputTextMsgDialog mInputTextMsgDialog;
    private ListView mListViewMsg;
    private ArrayList<TCChatEntity> mArrayListChatEntity = new ArrayList<>();
    private TCChatMsgListAdapter mChatMsgListAdapter;
    private List<PusherInfo> mPusherList = new ArrayList<>();
    private TCVideoWidgetList mPlayerList;
    protected LiveRoom mLiveRoom;
    private List<VideoAvatarListBeen> videoMoreAvatarList = new ArrayList<>();//直播间用户头像列表
    private List<VideoAvatarListBeen> videoAllAvatarList = new ArrayList<>();//直播间s列表
    private int mCurrentMemberCount = 0;//当前在线人数
    private int mTotalMemberCount = 0;//累计观看人数
    private int mTotalZanCount = 0;//累计点赞数
    private long mHeartCount = 0;
    protected boolean mPausing = false;
    private boolean mPlaying = false;
    private String mGroupId = "";
    private String mFileId = "";
    protected String mUserId = "";
    protected String mNickname = "";
    protected String mHeadPic = "";
    //弹幕
    private TCDanmuMgr mDanmuMgr;


    //手势动画
    private RelativeLayout mControllLayer;
    private TCSwipeAnimationController mTCSwipeAnimationController;
    protected ImageView mBgImageView;
    private ErrorDialogFragment mErrDlgFragment = new ErrorDialogFragment();
    private long mStartPushPts;

    protected Handler mHandler = new Handler();
    //选择推销的商品
    private List<VideoRoomGoodListBeen.DataBean.GoodsBean> goodList = new ArrayList<>();
    private int joinCount = 0;//记录加入房间im失败次数
    private int msgType;//消息类型
    private String msgContext;//名称
    private List<CustomerMsgBeen> msgBeenList = new ArrayList<>();
    private Animation transtoLeftAnim;
    private Animation transtoRightAnim;
    private boolean isYijia = false;
    private MyHandler myHandlerReconnection;
    //在线观众布局
    private TabLayout mTabLayout;
    private ViewPager viewpager;
    private List<Fragment> mFragments;
    private String[] title = {"在线观看"};
    private HomeVPAdapter homeVPAdapter;
    private boolean isFirst = true;
    private AudioManager audioManager;
    private boolean isSpeakerOpen = true;//默认开启手机扬声器


    @Override
    public int getLayoutId() {
        return R.layout.activity_prepare_video;
    }

    @Override
    public void initView() {
        StatusBarUtil.setLightStatusBar(CreatePusherActivity.this, true, true);
        mContext = CreatePusherActivity.this;
        mPresenter = new CreatePusherPresenter();
        mPresenter.attachView(this);
        rtmpURL = getIntent().getStringExtra("video_url");
        roomId = getIntent().getIntExtra("roomId", 0);
        tvTitle.setText(getIntent().getStringExtra("name"));
        image_cover = getIntent().getStringExtra("image");
        isYijia = getIntent().getBooleanExtra("yijian", false);
        Log.e("是否是", "+" + isYijia);

        audioManager = ((AudioManager) getSystemService(AUDIO_SERVICE));
        RoundedCorners roundedCorners = new RoundedCorners(20);
        //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
        RequestOptions options = RequestOptions.bitmapTransform(roundedCorners);
        options.placeholder(R.drawable.icon_cover)//图片加载出来前，显示的图片
                .fallback(R.drawable.icon_cover) //url为空的时候,显示的图片
                .error(R.drawable.icon_cover);
        Glide.with(mContext).load(image_cover).apply(options.transform(new CenterCrop(), roundedCorners)).into(ivCover);


        initPusher();              // 初始化 SDK 推流器
        initMainView();            // 初始化一些核心的 View
        //启动本地摄像头预览
        mPusherView = findViewById(R.id.pusher_tx_cloud_view);
        mLivePusher.startCameraPreview(mPusherView);
        //镜像效果zheng
        mLivePusher.setMirror(true);
        initDialog();//关闭直播的提示
        dialog_edit();//修改价格的提示


        EventBus.getDefault().register(this);
        TCUserMgr.getInstance().initContext(this);
        if (EmptyUtil.isNotEmpty(UtilsData.getPreference(this, "login").getString("nickname"))) {
            mNickname = mUserId;
        } else {
            mNickname = UtilsData.getPreference(this, "login").getString("nickname");
        }

        mHeadPic = UtilsData.getPreference(this, "login").getString("head_url") == null ? "" : UtilsData.getPreference(this, "login").getString("head_url");

        if (TextUtils.isEmpty(mNickname)) {
            mNickname = mUserId;
        }

        mLiveRoom = TCLiveRoomMgr.getLiveRoom(this);
        mLiveRoom.updateSelfUserInfo(mNickname, mHeadPic);

        mInputTextMsgDialog = new TCInputTextMsgDialog(this, R.style.InputDialog);
        mInputTextMsgDialog.setmOnTextSendListener(this);
        mListViewMsg = (ListView) findViewById(R.id.im_msg_listview);
        mListViewMsg.setVisibility(View.VISIBLE);
        // mHeartLayout = (TCHeartLayout) findViewById(R.id.heart_layout);
        mChatMsgListAdapter = new TCChatMsgListAdapter(this, mListViewMsg, mArrayListChatEntity);
        mListViewMsg.setAdapter(mChatMsgListAdapter);

        mCurrentMemberCount++;
        initAnimationListener();//初始化动画监听
        if (select_good_PW == null) {
            select_good_PW = new ShopCarPopupWindow(this, R.layout.pw_video_good_dai);
            select_good_PW.getRootView().findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    select_good_PW.shareClose();
                }
            });
            RecyclerView rvList = select_good_PW.getRootView().findViewById(R.id.rv_good_list);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            rvList.setLayoutManager(linearLayoutManager);
            videoGoodListAdapter = new VideoGoodListAdapter(this, goodList, dialogEdit, ettGoodPrice, ettGoodYouhuiPrice, ettKucun);
            rvList.setAdapter(videoGoodListAdapter);
            select_good_PW.getRootView().findViewById(R.id.tv_add_good).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Utils.isFastClick()) {
                        select_good_PW.shareClose();
                        Intent intent = new Intent(mContext, VideoShopGoodActivity.class);
                        intent.putExtra("ids", (Serializable) ids);
                        intent.putExtra("roomId", roomId + "");
                        startActivity(intent);
                    }
                }
            });
        }

        mTabLayout = findViewById(R.id.tl_video_type);
        viewpager = findViewById(R.id.viewpager);

        mFragments = new ArrayList<>();
        mFragments.add(LiveAllCountFragment.newInstance(1));//累计观看
        mTabLayout.setTabMode(TabLayout.MODE_FIXED);
        mTabLayout.setTabRippleColor(ColorStateList.valueOf(getResources().getColor(R.color.picture_color_transparent)));
        for (String tab : title) {
            mTabLayout.addTab(mTabLayout.newTab().setText(tab));
        }
        homeVPAdapter = new HomeVPAdapter(getSupportFragmentManager(), title, mFragments);
        viewpager.setAdapter(homeVPAdapter);
        mTabLayout.setupWithViewPager(viewpager);


    }

    //收到用户购买消息通知
    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onBuyMessage(BuyLiveGoodsMessage messageEvent) {
        Log.e("LogininfoBean", messageEvent.getBuyMessage() + "--onBuyMessage--");

        PusherEventBean pusherEventBean = new Gson().fromJson(messageEvent.getBuyMessage(), PusherEventBean.class);
        if (pusherEventBean.getStatus() == 1) {//用户购买
            msgBeenList.add(new CustomerMsgBeen(TCConstants.IMCMD_BUY, pusherEventBean.getMsg()));
        } else if (pusherEventBean.getStatus() == 2) {//主播异常断流

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMainEvent(JoinRoomSuccessEvent event) {
        Log.e("startPlay", "JoinRoomSuccessEvent");
        // if (mPlaying) return;
        enterIMRoom();
    }

    private void initMainView() {

        mBeautyPanelView = (BeautyPanel) findViewById(R.id.pusher_beauty_pannel);

        PusherBeautyKit manager = new PusherBeautyKit(mLivePusher);
        mBeautyPanelView.setProxy(manager);
        mBeautyPanelView.setOnItemClickListener(this::onItemClick);
    }

    private void initDialog() {
        dialog = Utils.addDialog(this, R.layout.dialog, R.string.want_to_drop_this_video, R.string.confirm, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                mLivePusher.stopPusher();
                stopTickWork();
                mLiveRoom.sendRoomCustomMsg(String.valueOf(TCConstants.IMCMD_PUSTER_EXIT), "直播结束", (LiveRoom.SendCustomMessageCallback) null);
                mLiveRoom.exitRoom(new LiveRoom.ExitRoomCallback() {
                    @Override
                    public void onError(int errCode, String errInfo) {
                        TXLog.w(TAG, "exit room error : " + errInfo);
                    }

                    @Override
                    public void onSuccess() {
                        TXLog.d(TAG, "exit room success ");
                    }
                });
                //隐藏部分
                startVisibility(false);
                rlEndVideo.setVisibility(View.VISIBLE);
                //结束直播统计信息
                mPresenter.videoEnd();
                StatusBarUtil.setLightStatusBar(CreatePusherActivity.this, false, true);
            }
        });

    }

    /**
     * 初始化 SDK 推流器
     */
    private void initPusher() {
        mLivePusher = new TXLivePusher(this);
        mLivePushConfig = new TXLivePushConfig();
        mLivePushConfig.setVideoEncodeGop(5);
        mLivePusher.setConfig(mLivePushConfig);
        mWaterMarkBitmap = decodeResource(getResources(), R.drawable.icon_shop_logo_ziti);

    }


    @Override
    public void showLoading() {
        if (!ProgressDialog.getInstance().materialDialog.isShowing()) {
            ProgressDialog.getInstance().show(this);
        }
    }

    @Override
    public void hideLoading() {
        ProgressDialog.getInstance().dismiss();
    }

    @Override
    public void onError(Throwable throwable) {

    }

    VideoEndBeen videoEndBeen;

    //结束直播统计信息
    @Override
    public void onVideoEndSuccess(VideoEndBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            videoEndBeen = bean;
            tvVideoEndLength.setText("直播时长:" + bean.getData().getLive_time());
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onCreatePusherSuccess(CreatePusherBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            Log.e("TCUserMgr", "onCreatePusherSuccess---推流成功");
            mPresenter.createImGroup(roomId + "", "0");//推流成功创建群组
            mLivePushConfig.setHomeOrientation(TXLiveConstants.VIDEO_ANGLE_HOME_DOWN);
            mLivePusher.setConfig(mLivePushConfig);
            mLivePusher.setRenderRotation(0);
            starPush();
            startTickWork();
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 创建群组成功
     */
    @Override
    public void onCreateImGroupSuccess(LogininfoBean bean) {
        Log.e("TCUserMgr", "onCreateImGroupSuccess---创建群组成功");
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            Log.e("TCUserMgr", TAG + "onCreateImGroupSuccess---" + bean.getData().getChat_id());
            //保存IM群组id
            UtilsData.getPreference(CreatePusherActivity.this, "IMlogin").put("chat_id", bean.getData().getChat_id());
            UtilsData.getPreference(CreatePusherActivity.this, "IMlogin").put("IMAccount", bean.getData().getLiveUsersigBean().getUid());
            UtilsData.getPreference(CreatePusherActivity.this, "IMlogin").put("IMSign", bean.getData().getLiveUsersigBean().getUsersig());
            TCUserMgr.getInstance().autoLogin(null);
            mUserId = UtilsData.getPreference(this, "IMlogin").getString("IMAccount");

            // mPresenter.getLiveImLogin(roomId+"","1");//创建群组成功之后在请求服务器获取自己的uid和sign
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * 加入群组成功
     */
    @Override
    public void onLiveImLoginSuccess(LogininfoBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            Log.e("TCUserMgr", TAG + "onLiveImLoginSuccess---" + bean.getData().getUid() + "---------" + bean.getData().getUsersig());
            //保存用户IM的uid 和sign


        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public void onVideoRoomGoodListSuccess(VideoRoomGoodListBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            ids.clear();
            goodList.clear();
            for (VideoRoomGoodListBeen.DataBean.GoodsBean goodsBean : bean.getData().getGoods()) {
                ids.add(goodsBean.getId() + "");
            }
            goodList.addAll(bean.getData().getGoods());

            videoGoodListAdapter.notifyDataSetChanged();

            //一键开播
            if (isYijia) {
                //上传封面url,标题
                if (goodList.size() == 0) {
                    Toast.makeText(mContext, "请选择推销的商品", Toast.LENGTH_SHORT).show();
                } else {
                    mPresenter.createPusher(image_cover, tvTitle.getText().toString().trim());
                }
            }
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onUpdateNumPriceSuccess(UpdateNumPriceBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            goodList.get(videoGoodListAdapter.getSelectPosition()).setMarketprice(ettGoodPrice.getText().toString().trim());
            goodList.get(videoGoodListAdapter.getSelectPosition()).setDiscountprice(ettGoodYouhuiPrice.getText().toString().trim());
            goodList.get(videoGoodListAdapter.getSelectPosition()).setStock(Integer.parseInt(ettKucun.getText().toString().trim()));
            videoGoodListAdapter.notifyDataSetChanged();
        } else {
            Toast.makeText(mContext, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }

    private ShopCarPopupWindow select_good_PW;//直播间选择的商品
    private VideoGoodListAdapter videoGoodListAdapter;
    Intent intent;

    @OnClick({R.id.tv_look_details, R.id.btn_goods, R.id.iv_cover, R.id.iv_back, R.id.tv_start, R.id.iv_video_set, R.id.ll_meiyan, R.id.ll_lvjing,
            R.id.ll_fanzhuan, R.id.tv_select_good, R.id.tv_finish, R.id.btn_message_input, R.id.tv_cumulative_watch,
            R.id.rl_onlinecount, R.id.tv_cumulative_watch_text, R.id.tv_online_num, R.id.tv_online_num_text})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.rl_onlinecount://人数弹窗布局
                rl_onlinecount.setVisibility(View.GONE);
                break;
            case R.id.tv_cumulative_watch://累计观看
            case R.id.tv_cumulative_watch_text://累计观看
            case R.id.tv_online_num://在线观看
            case R.id.tv_online_num_text://在线观看
                isFirst = false;
                rl_onlinecount.setVisibility(View.VISIBLE);
                Log.e("videoMoreAvatarList", videoMoreAvatarList.size() + "----------");
                EventBus.getDefault().post(new LiveAllCountListMessage(videoMoreAvatarList));
                break;
            case R.id.tv_look_details:
                intent = new Intent(mContext, VideoDetailActivity.class);
                if (null != videoEndBeen) {
                    intent.putExtra("videoEndBeen", (Serializable) videoEndBeen.getData());
                }
                startActivity(intent);
                break;
            case R.id.btn_goods:
                //购物袋

                select_good_PW.showPopupWindow();
                break;
            case R.id.iv_cover:
                selectImage(ivCover);
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_start:
                //上传封面url,标题
                if (goodList.size() == 0) {
                    Toast.makeText(mContext, "请选择推销的商品", Toast.LENGTH_SHORT).show();
                } else {
                    mPresenter.createPusher(image_cover, tvTitle.getText().toString().trim());
                }

//                if (select_HSping_PW == null) {
//                    select_HSping_PW = new ShopCarPopupWindow(this, R.layout.pw_select_ping);
//                    select_HSping_PW.getRootView().setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View view) {
//                            select_HSping_PW.shareClose();
//                        }
//                    });
//                    select_HSping_PW.getRootView().findViewById(R.id.ll_shu).setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View view) {
//                            //竖屏
//                            select_HSping_PW.shareClose();
//
//                        }
//                    });
//                    select_HSping_PW.getRootView().findViewById(R.id.ll_heng).setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View view) {
//                            //横屏
//                            select_HSping_PW.shareClose();
//                            mLivePushConfig.setHomeOrientation(TXLiveConstants.VIDEO_ANGLE_HOME_RIGHT);
//                            mLivePusher.setConfig(mLivePushConfig);
//                            // 因为采集旋转了，为了保证本地渲染是正的，则设置渲染角度为90度。
//                            mLivePusher.setRenderRotation(90);
//                            starPush();
//                        }
//                    });
//                }
//                select_HSping_PW.showPopupWindow();
                break;
            case R.id.iv_video_set:
                if (select_Set_PW == null) {
                    select_Set_PW = new ShopCarPopupWindow(this, R.layout.pw_select_set);
                    select_Set_PW.getRootView().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            select_Set_PW.shareClose();
                        }
                    });
                    select_Set_PW.getRootView().findViewById(R.id.ll_exit).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (Utils.isFastClick()) {
                                select_Set_PW.shareClose();
                                dialog.show();
                            }
                        }
                    });
                    TextView tvMicrophone = select_Set_PW.getRootView().findViewById(R.id.tv_microphone);
                    select_Set_PW.getRootView().findViewById(R.id.ll_microphone).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            isSpeakerOpen = !isSpeakerOpen;
                            if (isSpeakerOpen) {
                                //开启麦克风
                                audioManager.setMicrophoneMute(false);
                                tvMicrophone.setText("关闭麦克风");

                            } else {
                                //关闭麦克风
                                audioManager.setMicrophoneMute(true);
                                tvMicrophone.setText("开启麦克风");

                            }
                            select_Set_PW.shareClose();
                        }
                    });
                    select_Set_PW.getRootView().findViewById(R.id.ll_fanzhuan).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            // 表明当前是前摄像头

                            if (mFrontCamera) {
                                mFrontCamera = false;
                            } else {
                                mFrontCamera = true;
                            }
                            mLivePusher.switchCamera();
                        }
                    });
                    select_Set_PW.getRootView().findViewById(R.id.ll_meiyan).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            select_Set_PW.dismiss();
                            if (!mBeautyPanelView.isShown()) {
                                mBeautyPanelView.setVisibility(View.VISIBLE);
                                mBeautyPanelView.setPosition_0();
                            }
                        }
                    });
                    select_Set_PW.getRootView().findViewById(R.id.ll_lvjing).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            select_Set_PW.dismiss();
                            if (!mBeautyPanelView.isShown()) {
                                mBeautyPanelView.setVisibility(View.VISIBLE);
                                mBeautyPanelView.setPosition_1();
                            }
                        }
                    });
                }
                select_Set_PW.showPopupWindow();
                break;
            case R.id.ll_meiyan:
                if (!mBeautyPanelView.isShown()) {
                    mBeautyPanelView.setVisibility(View.VISIBLE);
                    mBeautyPanelView.setPosition_0();
                }
                break;
            case R.id.ll_lvjing:
                if (!mBeautyPanelView.isShown()) {
                    mBeautyPanelView.setVisibility(View.VISIBLE);
                    mBeautyPanelView.setPosition_1();
                }
                break;
            case R.id.ll_fanzhuan:

                // 表明当前是前摄像头
                if (mFrontCamera) {
                    mFrontCamera = false;
                } else {
                    mFrontCamera = true;
                }
                mLivePusher.switchCamera();
                break;
            case R.id.tv_select_good:
                intent = new Intent(this, VideoShopGoodActivity.class);
                intent.putExtra("ids", (Serializable) ids);
                intent.putExtra("roomId", roomId + "");
                startActivity(intent);
                break;
            case R.id.tv_finish:
                finish();
                break;
            case R.id.btn_message_input://消息文本
                showInputMsgDialog();
                break;
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        //请求直播间的商品列表
        mPresenter.videoRoomGoodList(roomId + "");
    }

    private void starPush() {
        //隐藏部分
        startVisibility(true);
        int ret = mLivePusher.startPusher(rtmpURL.trim());
        if (ret == -5) {
            Log.i("推流", "startRTMPPush: license 校验失败");
        }

        RoundedCorners roundedCorners = new RoundedCorners(20);
        //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
        RequestOptions options = RequestOptions.bitmapTransform(roundedCorners).override(200, 200);
        options.placeholder(R.drawable.icon_defult)//图片加载出来前，显示的图片
                .fallback(R.drawable.icon_defult) //url为空的时候,显示的图片
                .error(R.drawable.icon_defult);
        Glide.with(this).load(image_cover).apply(options.transform(new CircleCrop(), roundedCorners)).into(ivLogo);

        tvShopName.setText(getIntent().getStringExtra("name"));
    }

    public void startVisibility(boolean isStart) {
        if (isStart) {
            mIsPushing = true;
            ivBack.setVisibility(View.GONE);
            ivCover.setVisibility(View.GONE);
            viewFengMianBg.setVisibility(View.GONE);
            tvZhiboState.setVisibility(View.VISIBLE);
            tvFengmian.setVisibility(View.GONE);
            tvCumulativeWatch.setVisibility(View.VISIBLE);
            tvOnlineNum.setVisibility(View.VISIBLE);
            tvPayOrderNum.setVisibility(View.GONE);
            tvPayMoney.setVisibility(View.GONE);
            tvCumulativeWatchText.setVisibility(View.VISIBLE);
            tvOnlineNumText.setVisibility(View.VISIBLE);
            tvPayOrderNumText.setVisibility(View.GONE);
            tvPayMoneyText.setVisibility(View.GONE);
            tvTitle.setVisibility(View.GONE);
            rlSelectGood.setVisibility(View.GONE);
            llMeiyan.setVisibility(View.GONE);
            llLvjing.setVisibility(View.GONE);
            llFanzhuan.setVisibility(View.GONE);
            tvStart.setVisibility(View.GONE);
            ivVideoSet.setVisibility(View.VISIBLE);
            tool_bar.setVisibility(View.VISIBLE);
            rl_zan.setVisibility(View.VISIBLE);

        } else {
            mIsPushing = false;
            ivBack.setVisibility(View.VISIBLE);
            ivCover.setVisibility(View.VISIBLE);
            viewFengMianBg.setVisibility(View.VISIBLE);
            tvZhiboState.setVisibility(View.GONE);
            tvFengmian.setVisibility(View.VISIBLE);
            tvCumulativeWatch.setVisibility(View.GONE);
            tvOnlineNum.setVisibility(View.GONE);
            tvPayOrderNum.setVisibility(View.GONE);
            tvPayMoney.setVisibility(View.GONE);
            tvCumulativeWatchText.setVisibility(View.GONE);
            tvOnlineNumText.setVisibility(View.GONE);
            tvPayOrderNumText.setVisibility(View.GONE);
            tvPayMoneyText.setVisibility(View.GONE);
            tvTitle.setVisibility(View.VISIBLE);
            rlSelectGood.setVisibility(View.VISIBLE);
            llMeiyan.setVisibility(View.VISIBLE);
            llLvjing.setVisibility(View.VISIBLE);
            llFanzhuan.setVisibility(View.VISIBLE);
            tvStart.setVisibility(View.VISIBLE);
            ivVideoSet.setVisibility(View.GONE);
            tool_bar.setVisibility(View.INVISIBLE);
            rl_zan.setVisibility(View.GONE);
        }
    }


    /**
     * 获取资源图片
     *
     * @param resources
     * @param id
     * @return
     */
    private Bitmap decodeResource(Resources resources, int id) {
        TypedValue value = new TypedValue();
        resources.openRawResource(id, value);
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inTargetDensity = value.density;
        return BitmapFactory.decodeResource(resources, id, opts);
    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    public void onBackPressed() {
        if (select_Set_PW != null) {
            if (select_Set_PW.isShowing()) {
                select_Set_PW.shareClose();
                return;
            }
        }
        if (!mIsPushing) {
            super.onBackPressed();
        } else {
            if (!dialog.isShowing()) {
                dialog.show();
            }
        }
    }

    @Override
    protected void onDestroy() {
//        if (select_HSping_PW != null) {
//            if (select_HSping_PW.isShowing()) {
//                select_HSping_PW.dismiss();
//            }
//            select_HSping_PW = null;
//        }
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        EventBus.getDefault().unregister(this);
        hideNoticeToast();
        mLivePusher.stopPusher();
        mLivePusher.stopCameraPreview(true); //如果已经启动了摄像头预览，请在结束推流时将其关闭。
        stopTickWork();
        mHandler.removeCallbacksAndMessages(null);
        mHandler = null;
        if (null != myHandlerReconnection) {
            myHandlerReconnection.removeCallbacksAndMessages(null);
            myHandlerReconnection = null;
        }
        super.onDestroy();
    }

    @Override
    public void onItemClick(int position) {
        if (mBeautyPanelView.isShown()) {
            mBeautyPanelView.setVisibility(View.GONE);
        }
    }


    public void selectImage(ImageView imageView) {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage()).maxSelectNum(1)
                .loadImageEngine(GlideEngine.createGlideEngine())
                .minSelectNum(1).imageSpanCount(4)
                .selectionMode(PictureConfig.SINGLE)
                .compress(true)
                .minimumCompressSize(1000)
                .compressQuality(60)
                .isCamera(true)
                .previewImage(true)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        // onResult Callback
                        if (result.size() != 0) {
                            UtilsLog.error("dizhi", result.get(0).getCompressPath());
                            showLoading();
                            upLoadFiles(Constants.BASE_URL + "/addons/shimmer_liveshop/index.php/api/6/3/plugin/merch/common/apply/uploadImg", new File(result.get(0).getCompressPath()), new XFDShopInActivity.ConnectListener() {
                                @Override
                                public void connectSuccess(String result) {
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            hideLoading();
                                            try {
                                                Gson gson = new Gson();
                                                UploadImgBeen uploadImgBeen = gson.fromJson(result, UploadImgBeen.class);
                                                if (uploadImgBeen.getErrno().equals("200")) {
                                                    image_cover = uploadImgBeen.getData().getSrc();
                                                    RoundedCorners roundedCorners = new RoundedCorners(20);
                                                    //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
                                                    RequestOptions options = RequestOptions.bitmapTransform(roundedCorners);
                                                    Glide.with(mContext).load(uploadImgBeen.getData().getSrc()).apply(options.transform(new CenterCrop(), roundedCorners)).into(imageView);

                                                } else {
                                                    Toast.makeText(mContext, uploadImgBeen.getMessage(), Toast.LENGTH_SHORT).show();
                                                }
                                            } catch (Exception e) {
                                                Toast.makeText(mContext, "上传失败", Toast.LENGTH_SHORT).show();

                                            }
                                        }
                                    });

                                }

                                @Override
                                public void connectFailed(String error) {
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            hideLoading();

                                        }
                                    });
                                }
                            });
                        }
                    }

                    @Override
                    public void onCancel() {
                        // onCancel Callback
                    }
                });
    }


    public void upLoadFiles(final String url, File file, final XFDShopInActivity.ConnectListener connectListener) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder().proxy(Proxy.NO_PROXY).connectTimeout(60 * 1000, TimeUnit.MILLISECONDS)
                .readTimeout(5 * 60 * 1000, TimeUnit.MILLISECONDS)
                .writeTimeout(5 * 60 * 1000, TimeUnit.MILLISECONDS)
                .build();
        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
        multipartBodyBuilder.setType(MultipartBody.FORM);
        //遍历map中所有参数到builder
        multipartBodyBuilder.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"), file));
        //构建请求体
        RequestBody requestBody = multipartBodyBuilder.build();
        Request.Builder RequestBuilder = new Request.Builder();
        RequestBuilder.url(url);// 添加URL地址
        RequestBuilder.post(requestBody);
        RequestBuilder.addHeader("Authori-zation", "Bearer " + APP_TOKEN);
        Request request = RequestBuilder.build();

        final Call call = okHttpClient.newCall(request);
        //异步get请求
        call.enqueue(new Callback() {
                         @Override
                         public void onFailure(Call call, IOException e) {
                             connectListener.connectFailed(e.toString());
                             UtilsLog.error("错误", e.toString());
                         }

                         @Override
                         public void onResponse(Call call, Response response) throws IOException {
                             String result = response.body().string();
                             connectListener.connectSuccess(result);
                             UtilsLog.error("成功", result);
                         }
                     }
        );
    }

    /**
     * 加入IM聊天室
     */
    protected void enterIMRoom() {
        mGroupId = UtilsData.getPreference(CreatePusherActivity.this, "IMlogin").getString("chat_id");
        mLiveRoom.setLiveRoomListener(this);
        // mGroupId = "@TGS#3NVP655FZ";
        Log.e("TCUserMgr", "进入" + mGroupId);
        mLiveRoom.setmSelfRoleType(1);//游客0，主播1，观众2
        mLiveRoom.enterRoom(mGroupId, mPusherView, new LiveRoom.EnterRoomCallback() {
            @Override
            public void onError(int errCode, String errInfo) {
                joinCount++;
                myHandlerReconnection = new MyHandler(CreatePusherActivity.this);
                if (joinCount < 10) {
                    myHandlerReconnection.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            /**
                             *要执行的操作
                             */
                            enterIMRoom();
                        }
                    }, 500);//0.5秒后执行Runnable中的run方法
                }
                // showErrorAndQuit(TCConstants.ERROR_MSG_JOIN_GROUP_FAILED + errCode);
                Log.e("TCUserMgr", "进入LiveRoom失败");
                TCUserMgr.getInstance().uploadLogs(TCConstants.ELK_ACTION_LIVE_PLAY, TCUserMgr.getInstance().getUserId(), -10001, "进入LiveRoom失败", null);
            }

            @Override
            public void onSuccess() {
                mBgImageView.setVisibility(View.GONE);
                mLiveRoom.sendRoomCustomMsg(String.valueOf(TCConstants.IMCMD_ENTER_LIVE), "", (LiveRoom.SendCustomMessageCallback) null);
                Log.e("TCUserMgr", "进入LiveRoom成功");
                TCUserMgr.getInstance().uploadLogs(TCConstants.ELK_ACTION_LIVE_PLAY, TCUserMgr.getInstance().getUserId(), 10000, "进入LiveRoom成功", null);
                // mvpPresenter.getJoinLive(SharedPreferencesManager.getSsotoken(),playerId);

            }
        });

        Log.e("startPlay", "startPlay");
    }

    /**
     * 发消息弹出框
     */
    private void showInputMsgDialog() {
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        if (null != mInputTextMsgDialog) {
            WindowManager.LayoutParams lp = mInputTextMsgDialog.getWindow().getAttributes();

            lp.width = (display.getWidth()); //设置宽度
            mInputTextMsgDialog.getWindow().setAttributes(lp);
            mInputTextMsgDialog.setCancelable(true);
            mInputTextMsgDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
            mInputTextMsgDialog.show();
        }

    }

    @Override
    public void onGetPusherList(List<PusherInfo> pusherList) {
        for (PusherInfo pusherInfo : pusherList) {
            mPusherList.add(pusherInfo);
            onPusherJoin(pusherInfo);
        }
    }

    @Override
    public void onPusherJoin(PusherInfo pusherInfo) {
        if (pusherInfo == null || pusherInfo.userID == null) {
            return;
        }

        final TCVideoWidget videoView = mPlayerList.applyVideoView(pusherInfo.userID);
        if (videoView == null) {
            return;
        }

        if (mPusherList != null) {
            boolean exist = false;
            for (PusherInfo item : mPusherList) {
                if (pusherInfo.userID.equalsIgnoreCase(item.userID)) {
                    exist = true;
                    break;
                }
            }
            if (exist == false) {
                mPusherList.add(pusherInfo);
            }
        }

        videoView.startLoading();
        mLiveRoom.addRemoteView(videoView.videoView, pusherInfo, new LiveRoom.RemoteViewPlayCallback() {
            @Override
            public void onPlayBegin() {
                videoView.stopLoading(false); //推流成功，stopLoading 小主播隐藏踢人的button
            }

            @Override
            public void onPlayError() {
                videoView.stopLoading(false);
            }
        }); //开启远端视频渲染
    }

    @Override
    public void onPusherQuit(PusherInfo pusherInfo) {
        if (mPusherList != null) {
            Iterator<PusherInfo> it = mPusherList.iterator();
            while (it.hasNext()) {
                PusherInfo item = it.next();
                if (pusherInfo.userID.equalsIgnoreCase(item.userID)) {
                    it.remove();
                    break;
                }
            }
        }

        mLiveRoom.deleteRemoteView(pusherInfo);//关闭远端视频渲染
        mPlayerList.recycleVideoView(pusherInfo.userID);
    }

    @Override
    public void onRecvJoinPusherRequest(String userID, String userName, String userAvatar) {

    }

    @Override
    public void onKickOut() {
        Toast.makeText(getApplicationContext(), "不好意思，您被主播踢开", Toast.LENGTH_LONG).show();
        //stopLinkMic();
    }

    @Override
    public void onRecvPKRequest(String userID, String userName, String userAvatar, String streamUrl) {

    }

    @Override
    public void onRecvPKFinishRequest(String userID) {

    }

    @Override
    public void onRecvRoomTextMsg(String roomID, String userID, String userName, String userAvatar, String message) {
        Log.e("onGroupTextMessage", "onRecvRoomTextMsg群消息==" + message);
        TCSimpleUserInfo userInfo = new TCSimpleUserInfo(userID, userName, userAvatar);
        handleTextMsg(userInfo, message);
    }

    @Override
    public void onRecvRoomCustomMsg(String roomID, String userID, String userName, String userAvatar, String cmd, String message) {
        Log.e("onGroupTextMessage", "onRecvRoomCustomMsg群消息==" + message);
        //  mvpPresenter.getLiveRenQi(SharedPreferencesManager.getSsotoken(),playerId);
        TCSimpleUserInfo userInfo = new TCSimpleUserInfo(userID, userName, userAvatar);
        int type = Integer.valueOf(cmd);
        switch (type) {
            case TCConstants.IMCMD_ENTER_LIVE:
                handleMemberJoinMsg(userInfo);
                break;
            case TCConstants.IMCMD_EXIT_LIVE:
                handleMemberQuitMsg(userInfo);
                break;
            case TCConstants.IMCMD_PRAISE:
                handlePraiseMsg(userInfo);
                break;
            case TCConstants.IMCMD_PAILN_TEXT:
                handleTextMsg(userInfo, message);
                break;
            case TCConstants.IMCMD_DANMU:
                handleDanmuMsg(userInfo, message);
                break;
            case TCConstants.IMCMD_FOCUS://自定义关注直播消息
                handlePusterFocusMsg(userInfo);
                break;
            case TCConstants.IMCMD_ADDCART://自定义商品加入到购物车消息
                handleAddCartMsg(userInfo, message);
                break;
            default:
                break;
        }
    }

    @Override
    public void onRoomClosed(String roomID) {
        //stopLinkMic();
        showErrorAndQuit(TCConstants.ERROR_MSG_LIVE_STOPPED);
    }

    @Override
    public void onDebugLog(String log) {
        TXLog.d(TAG, log);
    }

    @Override
    public void onError(int errorCode, String errorMessage) {
        stopTickWork();
        showErrorAndQuit(TCConstants.ERROR_RTMP_PLAY_FAILED);
    }

    @Override
    public void onLivePlayEvent(int event, Bundle params) {
        report(event);
    }

    /**
     * 小直播ELK上报内容
     *
     * @param event
     */
    private void report(int event) {
        switch (event) {
            case TXLiveConstants.PLAY_EVT_RCV_FIRST_I_FRAME:
                Log.e("TCUserMgr", "视频播放成功");
                //    TCUserMgr.getInstance().uploadLogs(TCConstants.ELK_ACTION_LIVE_PLAY, TCUserMgr.getInstance().getUserId(), 0, "视频播放成功", null);
                break;
            case TXLiveConstants.PLAY_ERR_NET_DISCONNECT:
                Log.e("TCUserMgr", "网络断连,且经多次重连抢救无效,可以放弃治疗,更多重试请自行重启播放");
                // TCUserMgr.getInstance().uploadLogs(TCConstants.ELK_ACTION_LIVE_PLAY, TCUserMgr.getInstance().getUserId(), -1, "网络断连,且经多次重连抢救无效,可以放弃治疗,更多重试请自行重启播放", null);
                break;
            case TXLiveConstants.PLAY_ERR_GET_RTMP_ACC_URL_FAIL:
                Log.e("TCUserMgr", "获取加速拉流地址失败");
                // TCUserMgr.getInstance().uploadLogs(TCConstants.ELK_ACTION_LIVE_PLAY, TCUserMgr.getInstance().getUserId(), -2, "获取加速拉流地址失败", null);
                break;
            case TXLiveConstants.PLAY_ERR_FILE_NOT_FOUND:
                Log.e("TCUserMgr", "播放文件不存在");
                // TCUserMgr.getInstance().uploadLogs(TCConstants.ELK_ACTION_LIVE_PLAY, TCUserMgr.getInstance().getUserId(), -3, "播放文件不存在", null);
                break;
            case TXLiveConstants.PLAY_ERR_HEVC_DECODE_FAIL:
                Log.e("TCUserMgr", "H265解码失败");
                // TCUserMgr.getInstance().uploadLogs(TCConstants.ELK_ACTION_LIVE_PLAY, TCUserMgr.getInstance().getUserId(), -4, "H265解码失败", null);
                break;
            case TXLiveConstants.PLAY_ERR_HLS_KEY:
                Log.e("TCUserMgr", "HLS解码Key获取失败");
                //TCUserMgr.getInstance().uploadLogs(TCConstants.ELK_ACTION_LIVE_PLAY, TCUserMgr.getInstance().getUserId(), -5, "HLS解码Key获取失败", null);
                break;
            case TXLiveConstants.PLAY_ERR_GET_PLAYINFO_FAIL:
                Log.e("TCUserMgr", "获取点播文件信息失败");
                //TCUserMgr.getInstance().uploadLogs(TCConstants.ELK_ACTION_LIVE_PLAY, TCUserMgr.getInstance().getUserId(), -6, "获取点播文件信息失败", null);
                break;

        }
    }

    protected void showErrorAndQuit(String errorMsg) {
        mLivePusher.stopPusher();
        stopTickWork();
        Intent rstData = new Intent();
        rstData.putExtra(TCConstants.ACTIVITY_RESULT, errorMsg);
        //TODO:返回直播列表页面刷新页面
        //  setResult(TCLiveListFragment.START_LIVE_PLAY,rstData);

        if (!mErrDlgFragment.isAdded() && !this.isFinishing()) {
            Bundle args = new Bundle();
            args.putString("errorMsg", errorMsg);
            mErrDlgFragment.setArguments(args);
            mErrDlgFragment.setCancelable(false);

            //此处不使用用.show(...)的方式加载dialogfragment，避免IllegalStateException
            FragmentTransaction transaction = getFragmentManager().beginTransaction();
            transaction.add(mErrDlgFragment, "loading");
            transaction.commitAllowingStateLoss();
        }
    }

    private void notifyMsg(final TCChatEntity entity) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
//                if(entity.getType() == TCConstants.PRAISE) {
//                    if(mArrayListChatEntity.contains(entity))
//                        return;
//                }
                if (mArrayListChatEntity.size() > 1000) {
                    while (mArrayListChatEntity.size() > 900) {
                        mArrayListChatEntity.remove(0);
                    }
                }

                mArrayListChatEntity.add(entity);
                mChatMsgListAdapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 收到用户加入房间的自定义消息
     */
    public void handleMemberJoinMsg(TCSimpleUserInfo userInfo) {
        //更新头像列表 返回false表明已存在相同用户，将不会更新数据
//        if (!mAvatarListAdapter.addItem(userInfo))
//            return;

        mCurrentMemberCount++;
        mTotalMemberCount++;
        tvCumulativeWatch.setText(Utils.toNumber(mTotalMemberCount));
        tvOnlineNum.setText(Utils.toNumber(mCurrentMemberCount));

        boolean isAdded = false;

        for (int i = 0; i < videoMoreAvatarList.size(); i++) {
            if (userInfo.userid.equals(videoMoreAvatarList.get(i).getUserId())) {
                isAdded = true;
                break;
            }
        }
        if (!isAdded) {
            videoMoreAvatarList.add(0, new VideoAvatarListBeen(userInfo.headpic, userInfo.nickname, userInfo.userid));
            if (videoMoreAvatarList.size() > 200) {
                videoMoreAvatarList.remove(200);
            }
        }

        if (isFirst) {
            UtilsData.getPreference(this, "roomlist").put("headlist", new Gson().toJson(videoMoreAvatarList));
        }


        //左下角显示用户加入消息
        TCChatEntity entity = new TCChatEntity();
        entity.setSenderName("通知");
        if (TextUtils.isEmpty(userInfo.nickname)) {
            msgContext = userInfo.userid;
            entity.setContext(userInfo.userid + "加入直播");
        } else {
            msgContext = userInfo.nickname;
            entity.setContext(userInfo.nickname + "加入直播");
        }
        //添加到消息集合中弹窗处理消息
        addMsgList(TCConstants.IMCMD_ENTER_LIVE, msgContext);
//        entity.setType(TCConstants.MEMBER_ENTER);
//        notifyMsg(entity);

    }

    public void handleMemberQuitMsg(TCSimpleUserInfo userInfo) {
        if (mCurrentMemberCount > 0)
            mCurrentMemberCount--;
        else
            Log.d(TAG, "接受多次退出请求，目前人数为负数");

        //   mMemberCount.setText(String.format(Locale.CHINA,"%d",mCurrentMemberCount));

        //   mAvatarListAdapter.removeItem(userInfo.userid);
        //在线人数
        tvOnlineNum.setText(String.format(Locale.CHINA, "%d", mCurrentMemberCount));
        int logoutIndex = 0;
        for (int i = 0; i < videoMoreAvatarList.size(); i++) {
            if (userInfo.userid.equals(videoMoreAvatarList.get(i).getUserId())) {
                logoutIndex = i;
                break;
            }
        }
        if (EmptyUtil.isNotEmpty(videoMoreAvatarList)) {
            videoMoreAvatarList.remove(logoutIndex);
        }

//        TCChatEntity entity = new TCChatEntity();
//        entity.setSenderName("通知");
//        if (TextUtils.isEmpty(userInfo.nickname))
//            entity.setContext(userInfo.userid + "退出直播");
//        else
//            entity.setContext(userInfo.nickname + "退出直播");
//        entity.setType(TCConstants.MEMBER_EXIT);
//        notifyMsg(entity);
    }

    /**
     * zf自定义商品被加入到购物车方法
     */
    public void handleAddCartMsg(TCSimpleUserInfo userInfo, String message) {
        //添加到消息集合中弹窗处理消息
        addMsgList(TCConstants.IMCMD_ADDCART, userInfo.nickname + "将" + message);
    }

    /**
     * zf自定义关注房间方法
     */
    public void handlePusterFocusMsg(TCSimpleUserInfo userInfo) {

        TCChatEntity entity = new TCChatEntity();
        entity.setSenderName("通知");
        if (TextUtils.isEmpty(userInfo.nickname)) {
            msgContext = userInfo.userid;
            //entity.setContext(userInfo.userid + "关注了直播间");
        } else {
            msgContext = userInfo.nickname;
            //entity.setContext(userInfo.nickname + "关注了直播间");
        }
        //添加到消息集合中弹窗处理消息
        addMsgList(TCConstants.IMCMD_FOCUS, msgContext);
//        entity.setType(TCConstants.MEMBER_ENTER);
//        notifyMsg(entity);

    }

    public void handlePraiseMsg(TCSimpleUserInfo userInfo) {
        TCChatEntity entity = new TCChatEntity();
        mTotalZanCount++;
        entity.setSenderName("通知");
        if (TextUtils.isEmpty(userInfo.nickname))
            entity.setContext(userInfo.userid + "点了个赞");
        else
            entity.setContext(userInfo.nickname + "点了个赞");
//        if (mHeartLayout != null) {
//            mHeartLayout.addFavor();
//        }
        mHeartCount++;
//
//        entity.setType(TCConstants.MEMBER_ENTER);
//        notifyMsg(entity);
        tv_zancount.setText(Utils.toNumber(mTotalZanCount));

    }

    public void handleDanmuMsg(TCSimpleUserInfo userInfo, String text) {
        handleTextMsg(userInfo, text);
        if (mDanmuMgr != null) {
            mDanmuMgr.addDanmu(userInfo.headpic, userInfo.nickname, text);
        }
    }


    public void handleTextMsg(TCSimpleUserInfo userInfo, String text) {
        TCChatEntity entity = new TCChatEntity();
        entity.setSenderName(userInfo.nickname);
        entity.setContext(text);
        entity.setType(TCConstants.TEXT_TYPE);

        notifyMsg(entity);


    }

    /**
     * TextInputDialog发送回调
     *
     * @param msg       文本信息
     * @param danmuOpen 是否打开弹幕
     */
    @Override
    public void onTextSend(String msg, boolean danmuOpen) {
        if (msg.length() == 0)
            return;
        try {
            byte[] byte_num = msg.getBytes("utf8");
            if (byte_num.length > 160) {
                Toast.makeText(this, "请输入内容", Toast.LENGTH_SHORT).show();
                return;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return;
        }

        //消息回显
        TCChatEntity entity = new TCChatEntity();
        entity.setSenderName("我:");
        entity.setContext(msg);
        entity.setType(TCConstants.TEXT_TYPE);
        notifyMsg(entity);

        if (danmuOpen) {
            if (mDanmuMgr != null) {
                mDanmuMgr.addDanmu(mHeadPic, mNickname, msg);
            }
            mLiveRoom.sendRoomCustomMsg(String.valueOf(TCConstants.IMCMD_DANMU), msg, new LiveRoom.SendCustomMessageCallback() {
                @Override
                public void onError(int errCode, String errInfo) {
//                    Log.w(TAG, "sendRoomDanmuMsg error: " + errInfo);
                }

                @Override
                public void onSuccess() {
                    Log.d(TAG, "sendRoomDanmuMsg success");
                }
            });
        } else {
            mLiveRoom.sendRoomTextMsg(msg, new LiveRoom.SendTextMessageCallback() {
                @Override
                public void onError(int errCode, String errInfo) {
                    Log.e("sendGroupTextMessage", "sendRoomTextMsg error:" + errCode + errInfo);
                }

                @Override
                public void onSuccess() {
                    Log.e("sendGroupTextMessage", "sendRoomTextMsg success:");
                }
            });
        }
    }

    private Toast mNoticeToast;
    private Timer mNoticeTimer;

    private void showNoticeToast(String text) {
        if (mNoticeToast == null) {
            mNoticeToast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG);
        }

        if (mNoticeTimer == null) {
            mNoticeTimer = new Timer();
        }

        mNoticeToast.setText(text);
        mNoticeTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                mNoticeToast.show();
            }
        }, 0, 3000);

    }

    private void hideNoticeToast() {
        if (mNoticeToast != null) {
            mNoticeToast.cancel();
            mNoticeToast = null;
        }
        if (mNoticeTimer != null) {
            mNoticeTimer.cancel();
            mNoticeTimer = null;
        }
    }

    private List<String> ids = new ArrayList<>();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == START_CODE) {
            if (resultCode == RESULT_OK) {
                ids = data.getStringArrayListExtra("data");
            }
        }
    }

    private Dialog dialogEdit;
    private EditText ettGoodPrice;
    private EditText ettGoodYouhuiPrice;
    private EditText ettKucun;
    private TextView tvDialogQueren;

    public void dialog_edit() {
        dialogEdit = new Dialog(mContext, R.style.ExitDialog);
        View layout = View.inflate(mContext, R.layout.dialog_good_bianji, null);
        dialogEdit.setContentView(layout);
        dialogEdit.setCanceledOnTouchOutside(true);
        layout.findViewById(R.id.tvw_dialog_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialogEdit.dismiss();
            }
        });
        ettGoodPrice = layout.findViewById(R.id.ett_good_price);
        ettGoodYouhuiPrice = layout.findViewById(R.id.ett_good_youhui_price);
        ettKucun = layout.findViewById(R.id.ett_kucun);
        tvDialogQueren = layout.findViewById(R.id.tv_dialog_queren);

        tvDialogQueren.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    dialogEdit.dismiss();
                    mPresenter.updateNumPrice(goodList.get(videoGoodListAdapter.getSelectPosition()).getId() + "", ettGoodPrice.getText().toString().trim(), ettKucun.getText().toString().trim(), ettGoodYouhuiPrice.getText().toString().trim());
                }
            }
        });
    }

    private SendValidateTimerUtil mTimer = new SendValidateTimerUtil();
    private int mDisableTimeTemp = 0;
    private int countDown;//活动倒计时秒数

    /**
     * 开启倒计时
     */
    public void startTickWork() {
//        if (countDown == 0){
//            tvZhiboState.setText("·直播中"+"00:00:00");
//        }else {
//            stopTickWork();
        mTimer.startWork(0, 1000, new SendValidateTimerUtil.SDTimerListener() {
            @Override
            public void onWorkMain() {
                tickWork();
            }

            @Override
            public void onWork() {
            }
        });
        // }
    }

    /**
     * 每秒钟调用一次
     */
    private void tickWork() {
        mDisableTimeTemp++;
        setCountDown(mDisableTimeTemp);
        //执行弹窗效果
        if (mDisableTimeTemp % 4 == 0) {
            if (msgBeenList.size() > 0) {
                showPopAnimation();
            }
        }

    }

    public void stopTickWork() {
        mTimer.stopWork();
        mDisableTimeTemp = countDown;

    }

    /*设置秒数显示*/
    private void setCountDown(int countDown) {
        int h = countDown / 3600;
        int m = (countDown - h * 3600) / 60;
        int s = countDown - (h * 3600 + m * 60);
        String hour = "";
        String minute = "";
        String second = "";

        if ((h + "").length() > 1) {
            hour = h + ":";
        } else {
            hour = 0 + h + ":";
        }
        if ((m + "").length() > 1) {
            minute = m + ":";
        } else {
            minute = "0" + m + ":";
        }
        if ((s + "").length() > 1) {
            second = s + "";
        } else {
            second = "0" + s + "";
        }
        tvZhiboState.setText("·直播中 " + hour + minute + second);
    }


    /**
     * 收到消息后维护一个消息集合
     */
    private void addMsgList(int msgType, String msgContext) {
        msgBeenList.add(new CustomerMsgBeen(msgType, msgContext));
    }

    /**
     * 初始化动画监听
     */
    public void initAnimationListener() {
        transtoLeftAnim = AnimationUtils.loadAnimation(CreatePusherActivity.this, R.anim.pop_in);
        transtoRightAnim = AnimationUtils.loadAnimation(CreatePusherActivity.this, R.anim.pop_out);
        transtoLeftAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        /**
                         *要执行的操作
                         */
                        tv_pop.startAnimation(transtoRightAnim);
                    }
                }, 1000);//1秒后执行Runnable中的run方法
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        transtoRightAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                tv_pop.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    private void showPopAnimation() {
        tv_pop.setVisibility(View.VISIBLE);
        if (msgBeenList.get(0).getMsgType() == TCConstants.IMCMD_ENTER_LIVE) {//加入直播间通知
            tv_pop.setText(msgBeenList.get(0).getMsgContext() + "来了~");
            tv_pop.setBackgroundResource(R.drawable.shape_fe2451conner16);
        } else if (msgBeenList.get(0).getMsgType() == TCConstants.IMCMD_FOCUS) {//关注直播间通知
            tv_pop.setText(msgBeenList.get(0).getMsgContext() + "关注了主播");
            tv_pop.setBackgroundResource(R.drawable.shape_db21fdconner3);
        } else if (msgBeenList.get(0).getMsgType() == TCConstants.IMCMD_ADDCART) {//关注商品加入到购物车通知
            tv_pop.setText(msgBeenList.get(0).getMsgContext() + "号商品加入了购物车");
            tv_pop.setBackgroundResource(R.drawable.shape_fdcc21conner3);
        } else if (msgBeenList.get(0).getMsgType() == TCConstants.IMCMD_BUY) {//收到已购买商品通知
            tv_pop.setText(msgBeenList.get(0).getMsgContext() + "");
            tv_pop.setBackgroundResource(R.drawable.shape_fdcc21conner3);
        }
        tv_pop.startAnimation(transtoLeftAnim);
        msgBeenList.remove(0);
    }

    private CreatePusherActivity.MyHandler myHandler = new CreatePusherActivity.MyHandler(this);

    private static class MyHandler extends Handler {
        private final WeakReference<CreatePusherActivity> mActivity;

        public MyHandler(CreatePusherActivity activity) {
            mActivity = new WeakReference<CreatePusherActivity>(activity);

        }

        @Override
        public void handleMessage(Message msg) {
            CreatePusherActivity activity = mActivity.get();
            if (activity != null) {
                //do Something
            }
        }
    }
}
